package com.e3.basdoc.bank.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.e3.basdoc.bank.dao.BankDAO;
import com.e3.basdoc.bank.entity.BankEntity;
import com.e3.basdoc.bank.model.BankModel;
import com.e3.basdoc.bank.model.BankQC;
import com.e3.basdoc.bank.service.BankCacheManager;
import com.e3.basdoc.bank.service.BankQueryService;
import com.e3.core.base.DAOHelper;
import com.e3.core.base.ServiceException;
import com.e3.core.base.SuperQueryService;

public class BankQueryServiceImpl extends SuperQueryService implements	BankQueryService {
	
	private BankDAO bankDAO;
	
	public BankDAO getBankDAO(){
		if(bankDAO==null){
			bankDAO = DAOHelper.createDAOInstance(BankDAO.class);
		}
		return bankDAO;
	}
	
	public List<BankModel> getBankChildren(BankModel bankModel)	throws ServiceException {
		long id = 0;
		if(bankModel!=null){
			id = bankModel.getId();
		}
		List<Long> pIds = new ArrayList<Long>(1);
		pIds.add(id);
		
		List<Long> ids = getBankDAO().getChildrenIds(pIds);
		return getBankByIds(ids);

	}
	
	public List<BankModel> getBankByIds(List<Long> ids) throws ServiceException {
		if(ids==null||ids.isEmpty()){
			return null;
		}
		List<BankModel> models = new ArrayList<BankModel>(ids.size());
		for (Long id : ids) {
			BankModel model = getBankById(id);
			models.add(model);
		}
		return models;
	}
	
	public BankModel getBankById(long id) throws ServiceException {
		BankModel model = BankCacheManager.INSTANCE.get(id);
		if(model!=null){
			return model;
		}
		
		BankEntity bankEntity = getBankDAO().getById(BankEntity.class, id);
		if(bankEntity==null){
			return null;
		}
		BankModel rModel = bankEntityToModel(bankEntity);
		if(rModel!=null){
			BankCacheManager.INSTANCE.put(rModel);
		}
		return rModel;
	}
	
	public List<BankModel> getBankByCondition(BankQC bankQC) throws ServiceException{
		List<Long> ids = getBankDAO().getBankIdsByCondition(bankQC);
		if(ids!=null&&ids.size()>0){
			return getBankByIds(ids);
		}
		return null;
	}

	private BankModel bankEntityToModel(BankEntity bankEntity) {
		
		if(bankEntity == null){
			return null;
		}
		
		BankModel model = new BankModel();
		model = entityToModel(model, bankEntity);

		model.setId(bankEntity.getId());
		model.setParentId(bankEntity.getParentId());
		model.setCode(bankEntity.getCode());
		model.setName(bankEntity.getName());
		model.setShortName(bankEntity.getShortName());

		model.setAddress(bankEntity.getAddress());
		model.setRemark(bankEntity.getRemark());
		model.setRegionId(bankEntity.getRegionId());
				
		return model;

	}

	public List<BankModel> getAllBanks() throws ServiceException {
		return getBankDAO().getAllBanks();
	}
}
